package com.sunducation.wts.penbox.activity;

import android.os.Build;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.sunducation.wts.penbox.R;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BasePresenter;
import com.wetao.lib_common.base.BaseViewImp;
import com.wetao.lib_common.bean.response.AppVersionInfo;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.AppInstallUtil;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.DownloadUtil;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.view.OnMultiClickListener;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author: zhouyh
 * created on: 3/5/21 3:10 PM
 * description:升级页面
 */
@Route(path = ConstantArouter.PATH_APP_UPDATEACTIVITY)
public class UpdateActivity extends BaseActivity {

    @Autowired
    String versionInfo;

    @Autowired
    String fromActivity;


    @BindView(R.id.btn_update)
    Button btn_update;
    @BindView(R.id.tv_update_content)
    TextView tv_content;

    @BindView(R.id.net_speed)
    TextView tv_speed;
    @BindView(R.id.net_size)
    TextView tv_download_size;
    @BindView(R.id.rl_progress)
    RelativeLayout rl_progress;
    @BindView(R.id.pb_main_download)
    ProgressBar pb_download;

    private AppVersionInfo versionBean;

    private String apkFileDir;
    private long lastTime=0;



    @Override
    public int getLayoutId() {
        return R.layout.activity_update;
    }

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @Override
    public BaseViewImp createView() {
        return null;
    }

    @Override
    public void init() {
        initTitleLayout();
        setTvTitle("版本更新",true);
        btn_update.requestFocus();
        if (versionInfo!=null){
            versionBean = (JsonUtils.getmGson()).fromJson(versionInfo,AppVersionInfo.class);
            setTvTitle("发现新版本" + versionBean.getVersion(),true);
            tv_content.setText(versionBean.getDescription());
        }

        if(ConstantArouter.PATH_USER_USERACTIVITY.equals(fromActivity)) {
            iv_back.setVisibility(View.VISIBLE);
            iv_back.setOnClickListener(new OnMultiClickListener() {
                @Override
                public void onMultiClick(View v) {
                    finish();
                }
            });
        } else {
            iv_back.setVisibility(View.INVISIBLE);
        }
    }

    @OnClick({R.id.btn_update})
    public void onClick(View v){
        if (v.getId() == R.id.btn_update){
            btn_update.setVisibility(View.INVISIBLE);
            rl_progress.setVisibility(View.VISIBLE);


            update();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        btn_update.setVisibility(View.VISIBLE);
        rl_progress.setVisibility(View.GONE);
        btn_update.requestFocus();

    }

    /**
     * 进行更新操作
     */
    private void update(){
        //String dirPath = this.getExternalFilesDir(null).getAbsolutePath();
        //String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        String dirPath = Constants.FILE_PATH;
        apkFileDir = dirPath + File.separator + "apk";

        File apkDir = new File(apkFileDir);
        if (!apkDir.exists()) {
            boolean mkdirs = apkDir.mkdirs();
            if (!mkdirs) {
                LogUtils.e("创建失败apk文件夹" + mkdirs);
            } else {
                LogUtils.i("创建成功apk文件夹");
            }
        }
        String apkFilePath = apkFileDir + File.separator + DownloadUtil.getNameFromUrl(versionBean.getDownloadUrl());
        File apkFile = new File(apkFilePath);
        /*if (apkFile.exists()) {
            //安装这个文件
            AppInstallUtil.installApk(getApplicationContext(),apkFilePath);
        } else {
            //下载文件
            download();
        }*/
        if(apkFile.exists()) {
           apkFile.delete();
        }
        download();
    }


    public  void download(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean hasInstallPermission = AppInstallUtil.isHasInstallPermissionWithO(getApplicationContext());
            if (!hasInstallPermission) {
                AppInstallUtil.startInstallPermissionSettingActivity(getApplicationContext());
                return;
            }
        }

        String url=versionBean.getDownloadUrl();
        LogUtils.i("download url ==" + url);
        // url="https://jtysunbox.oss-cn-beijing.aliyuncs.com/application/SunboxApp/penbox_goline_v1.0.7.apk";

        DownloadUtil.get().download(this, url,apkFileDir, new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(final String path) {
                AppInstallUtil.installApk(getApplicationContext(),path);

            }

            @Override
            public void onDownloading(final int sum, final int total, final int progress) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pb_download.setProgress(progress);
                        String sumSize= ComUtil.byte2FitMemorySize(sum);

                        String fileSize= ComUtil.byte2FitMemorySize(total);
                        if(tv_download_size!=null){
                            tv_download_size.setText(sumSize+"/"+fileSize);
                        }

                    }
                });
            }

            @Override
            public void onDownloadFailed() {

            }

            @Override
            public void onNetwork(boolean isNetwork) {
                if(!isNetwork){
                    DialogXUtil.popTipShow(getString(R.string.network_disconnect), 1500);
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_F11) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }
}
